package com.jtjrenren.android.taxi.driver.core.order.details;

import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.baidu.mapapi.utils.route.RouteParaOption;
import com.jtjrenren.android.taxi.driver.Constants;
import com.jtjrenren.android.taxi.driver.R;

import com.jtjrenren.android.taxi.driver.base.MvpActivity;
import com.jtjrenren.android.taxi.driver.bean.api.ApiOrderCost;
import com.jtjrenren.android.taxi.driver.core.order.pay.OrderCommitPayActivity;
import com.jtjrenren.android.taxi.driver.manger.AppManger;
import com.jtjrenren.android.taxi.driver.manger.TtsManger;
import com.jtjrenren.android.taxi.driver.bean.Order;
import com.jtjrenren.android.taxi.driver.utils.IntentUtils;
import com.jtjrenren.android.taxi.driver.utils.ModuleUtils;
import com.jtjrenren.android.taxi.driver.utils.MyDrivingRouteOverlay;
import com.jtjrenren.android.taxi.driver.utils.UIHelper;
import com.library.utils.LogUtil;


import butterknife.BindView;
import butterknife.OnClick;

import java.util.List;

/**
 * Created by Administrator on 2016/5/6.
 */
public class OrderDetailsActivity extends MvpActivity<OrderDetailsPresenter> implements OrderDetailsView {
    @BindView(R.id.title_title)
    TextView tv_title;
    @BindView(R.id.orderdetails_start)
    TextView tv_start;
    @BindView(R.id.orderdetails_end)
    TextView tv_end;
    @BindView(R.id.title_right)
    TextView tv_qxdd;
    @BindView(R.id.orderdetails_time)
    TextView tv_yytime;
    @BindView(R.id.orderdetails_ksyyd)
    LinearLayout ll_ksyyd;

    @BindView(R.id.orderdetails_jdck)
    LinearLayout ll_cksc;
    @BindView(R.id.orderdetails_jdck_btn)
    Button bt_cksc;

    @BindView(R.id.orderdetails_ddmdd)
    LinearLayout ll_ddmdd;
    @BindView(R.id.orderdetails_ddmdd_btn)
    Button bt_ddmdd;

    @BindView(R.id.orderdetails_qxdd)
    LinearLayout ll_qxdd;
    @BindView(R.id.orderdetails_qxdd_desc)
    TextView tv_qxdd_desc;

    @BindView(R.id.orderdetails_jf)
    LinearLayout ll_specost;
    @BindView(R.id.jf_cost_details)
    LinearLayout ll_costdetails;
    @BindView(R.id.order_status_jf_total)
    TextView tv_total_cost;

    @BindView(R.id.orderdetails_nav)
    ImageButton ib_nav;
    @BindView(R.id.order_details_mapview)
    MapView bdMapView;
    private BaiduMap bdMap;

    private boolean isFirstLoc = true;
    private MyLocationConfiguration.LocationMode locationMode = MyLocationConfiguration.LocationMode.FOLLOWING;
    private MyDrivingRouteOverlay drivingRouteOverlay;
    private BitmapDescriptor carMarker = BitmapDescriptorFactory
            .fromResource(R.mipmap.n_def_car);

    boolean isSxzx = false; //是否顺序执行 用于判断是否要延迟提交

    public static Intent getDiyIntent(Context context, String orderID) {
        Intent intent = new Intent(context, OrderDetailsActivity.class);
        intent.putExtra("orderid", orderID);
        return intent;
    }

    @Override
    public int getLayoutID() {
        return R.layout.aty_order_details;
    }

    @Override
    public void initM() {
        ((TextView) findViewById(R.id.title_title)).setText("订单详情");
        findViewById(R.id.title_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        bdMap = bdMapView.getMap();
        bdMap.setMyLocationEnabled(true);
        bdMap.setMyLocationConfigeration(new MyLocationConfiguration(locationMode, true, carMarker,
                0x00FFFFFF, 0x00FFFFFF));

        initHandler();

        if (getIntent().hasExtra("orderid"))
            presenter.init(getIntent().getStringExtra("orderid"));
        else
            presenter.init(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.destory();
        handler.removeMessages(0);
        handler.removeMessages(1);
        if (carMarker != null)
            carMarker.recycle();
       navDestory();
    }

    @Override
    protected void onResume() {
        super.onResume();
        bdMapView.onResume();
//        isNav=false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        bdMapView.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.CODE_ATY_ORDERPAY) {
            if (resultCode == RESULT_OK)
                finish();
        }
    }

    @Override
    protected void handMsg(Message msg) {
        super.handMsg(msg);
        switch (msg.what) {
            case 0:
                LogUtil.log("order","请求刷新订单费用信息");
                presenter.getOrderCost();
                handler.sendEmptyMessageDelayed(0, 5 * 1000);
                break;
            case 1:
                bt_ddmdd.setEnabled(true);
                break;
        }
    }

    @Override
    public void refershCommonView(Order order) {
        tv_start.setText(order.getStartAddr());
        tv_end.setText(order.getEndAddr());
    }

    @Override
    public void showStartYYD(Order order) {
        clearStatusView();
        ll_ksyyd.setVisibility(View.VISIBLE);
        tv_qxdd.setVisibility(View.VISIBLE);
        tv_yytime.setVisibility(View.VISIBLE);

        tv_yytime.setText(order.getUseDate());
    }

    @Override
    public void showQjCk() {
        clearStatusView();

        isSxzx = true;

        ll_cksc.setVisibility(View.VISIBLE);
        tv_qxdd.setVisibility(View.VISIBLE);
        if (AppManger.getInstance().isYzc())
            bt_cksc.setText("开始计费");

        if (drivingRouteOverlay != null)
            drivingRouteOverlay.refrshType(MyDrivingRouteOverlay.TYPE_QJK);
    }

    @Override
    public void shwoInCar() {
        clearStatusView();
        ll_ddmdd.setVisibility(View.VISIBLE);


        if (isSxzx) {
            bt_ddmdd.setEnabled(false);
            handler.sendEmptyMessageDelayed(1, 30 * 1000);
        }

        if (AppManger.getInstance().isYzc()) {
            bt_ddmdd.setText("结束计费");
            ll_specost.setVisibility(View.VISIBLE);
        }
        if (drivingRouteOverlay != null)
            drivingRouteOverlay.refrshType(MyDrivingRouteOverlay.TYPE_SC);
    }


    @Override
    public void showDdQx() {
        clearStatusView();
        ll_qxdd.setVisibility(View.VISIBLE);
    }

    @Override
    public void refreshNavStatus(boolean isNav) {
//        ib_nav.setEnabled(isNav);
    }

    @Override
    public void showTipTost(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showTipProg(String msg) {
        showProDialog(null, msg);
    }

    @Override
    public void disTipDialog() {
        disProDialog();
    }

    @Override
    public void showOrderFinsh(Order order) {
        IntentUtils.goOrderFinishPage(this, order);
        finish();
    }

    @Override
    public void goOrderPayPage(Order order) {
        LogUtil.log("applog", "进入支付页面");
        startActivity(OrderCommitPayActivity.getDiyIntent(this, order));
        finish();
    }

    @Override
    public void finishAty() {
        finish();
    }

    @Override
    public void refreshLoc(BDLocation bdLocation) {
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(bdLocation.getRadius())
                .direction(0).latitude(bdLocation.getLatitude())
                .longitude(bdLocation.getLongitude()).build();
        bdMap.setMyLocationData(locData);
        if (isFirstLoc) {
            isFirstLoc = false;
            LatLng ll = new LatLng(bdLocation.getLatitude(),
                    bdLocation.getLongitude());
            animRefreshMapTarget(ll);
        }
    }

    @Override
    public void refreshJfMsg(ApiOrderCost.DataListEntity cost) {
        LogUtil.log("order","显示费用信息："+cost.toString());

        tv_total_cost.setText(cost.getTotalMoney() + "");

        List<LinearLayout> list = ModuleUtils.showEstimatedCost(this, cost.getFeeDesc());

        ll_costdetails.removeAllViews();
        for (LinearLayout ll : list) {
            ll_costdetails.addView(ll);
        }
    }

    @Override
    public void startRefreshOrderCost() {
        LogUtil.log("order","乘客上车:开始刷新订单费用信息");
        handler.sendEmptyMessage(0);
    }

    @Override
    public void stopRefreshOrderCost() {
        handler.removeMessages(0);
    }

    @Override
    public void refreshRoutPlan(DrivingRouteResult drivingRouteResult) {
        drivingRouteOverlay = new MyDrivingRouteOverlay(bdMap);
        bdMap.setOnMarkerClickListener(drivingRouteOverlay);
        drivingRouteOverlay.setData(drivingRouteResult.getRouteLines().get(0));
        drivingRouteOverlay.addToMap();
        drivingRouteOverlay.zoomToSpan();
    }

    @Override
    public void animRefreshMapTarget(LatLng target) {
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(target)
                .zoom(16)
                .build();
        bdMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(mMapStatus));
    }

    @Override
    public void showCancleOrderTip() {
        UIHelper.showDialog(this, null, null, getString(R.string.shifouquxiaodingdan), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TtsManger.getInstance().stop();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.cancleOrder();
            }
        });
    }

    @OnClick(R.id.orderdetails_ksyyd_btn)
    public void startYYD() {
        presenter.startYYD();
    }

    @OnClick(R.id.orderdetails_jdck_btn)
    public void jdCk() {//接到乘客
        presenter.jdCk();
    }

    @OnClick(R.id.orderdetails_ddmdd_btn)
    public void ddMdd() {
        presenter.ddMdd();
    }

    @OnClick(R.id.orderdetails_qxdd_fh)
    public void qxddBack() {
        finish();
    }

    @OnClick(R.id.title_right)
    public void qxdd() {
        presenter.clickCancleOrder();
    }

    @OnClick(R.id.orderdetails_hjck)
    public void hjCk() {
        UIHelper.showCallPhoneDialog(this, presenter.getPassgerPhone());
    }

    @OnClick(R.id.orderdetails_nav)
    public void startNav() {
//        if (isNav){
//            displayShort("导航调起中，请稍候...");
//        }else {      }
            nav();
    }

    @OnClick(R.id.orderdetails_loc)
    public void rLoc() {
    }

    @Override
    public OrderDetailsPresenterImpl createPresenter() {
        return new OrderDetailsPresenterImpl(this);
    }

//    private boolean isNav=false;
    private void nav(){
        LatLng start=presenter.getStart();
        LatLng end =presenter.getEnd();

        if (start==null||end==null){
//            isNav=false;
            displayShort("地址不确定，不能导航");
            return;
        }
        LogUtil.log("nav","开始导航==》"+presenter.getStart().toString()+"----"+presenter.getEnd().toString());
//        isNav=true;
        displayShort("导航调起中，请稍候...");
        RouteParaOption para = new RouteParaOption()
                .startPoint(start)
                .endPoint(end);
        try {
            BaiduMapRoutePlan.openBaiduMapDrivingRoute(para, OrderDetailsActivity.this);
        } catch (Exception e) {
            LogUtil.log("nav","导航出现问题："+e.toString());
            displayShort("您尚未安装百度地图app或app版本过低");
        }
    }

    private void navDestory(){
        BaiduMapRoutePlan.finish(this);
    }

    /**
     * 清空当前view
     */
    private void clearStatusView() {
        ll_ksyyd.setVisibility(View.GONE);
        ll_cksc.setVisibility(View.GONE);
        ll_ddmdd.setVisibility(View.GONE);
        ll_qxdd.setVisibility(View.GONE);
        ll_specost.setVisibility(View.GONE);

        tv_qxdd.setVisibility(View.GONE);

        tv_yytime.setVisibility(View.GONE);

        if (drivingRouteOverlay != null) {
            drivingRouteOverlay.removeFromMap();
            drivingRouteOverlay = null;
        }
    }
}
